package com.lagou.servlet;

import com.lagou.bean.User;
import com.lagou.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.设置响应输出编码，避免中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        // 2.获取请求中的用户名和密码信息并打印出来
        String userName = request.getParameter("userName");
        System.out.println("获取到的用户名是"+userName);
        String password = request.getParameter("password");
        System.out.println("获取到的密码是"+password);
        // 3.创建UserService类型的对象去实现数据的校验功能
        UserService userService = new UserService();
        User user = userService.loginUserService(new User(userName, password));
        if(user==null){
            request.setAttribute("error","用户名和密码输入错误");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            requestDispatcher.forward(request,response);

        }else
        {
            request.getSession().setAttribute("userName",user.getUserName());
            response.sendRedirect("main.jsp");
        }


    }
}
